<template>
  <div>
    <el-row :gutter="10" center class="monitor">
      <div class="backBeforepage">
        <el-button type="text" icon="el-icon-caret-left" @click="prev">上一页</el-button>
      </div>
      <el-col :span="6" :offset="1">物理位置监控可视化操作界面</el-col>
      <el-col :span="8" :offset="2">工位信息维护</el-col>
    </el-row>
    <el-card>
      <el-form size="mini" ref="roomForm" :model="roomForm" :rules="rules" label-width="140px" label-position="left">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item prop="roomNo" label="房间号：">
              <el-input v-model="roomForm.roomNo" disabled placeholder="请输入房间号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="roomName" label="房间名称：">
              <el-input v-model="roomForm.roomName" disabled placeholder="请输入房间名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-col :span="20">
              <el-form-item prop="bkImageUrl" label="CAD底图：">
                <el-input v-model="roomForm.bkImageUrl" disabled placeholder="请选择CAD底图"></el-input>
                <!-- <el-select
                  v-model="roomForm.bkImageUrl"
                  disabled
                  @change="handleChange"
                  placeholder="请选择CAD底图"
                >
                  <el-option
                    v-for="item in bkImageUrlList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                    :disabled="item.disabled"
                  ></el-option>
                </el-select> -->
              </el-form-item>
            </el-col>
            <!-- <el-col :span="4">
               <el-button size="mini" type="primary"    icon="el-icon-plus" @click="addBkImg">新增底图</el-button>
            </el-col>-->
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item prop="stationSize" label="最大工位数：">
              <el-input-number v-model="roomForm.stationSize" :min="1" placeholder="请输入工位数"></el-input-number>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8" :offset="2">
            <el-button size="mini" type="success" icon="el-icon-plus" @click="createRoom">创建房间</el-button>
          </el-col> -->
        </el-row>
      </el-form>
    </el-card>
    <el-card v-model="visible" v-show="visible" style="margin-top:10px;height:1200px;">
      <el-form size="mini" ref="form2" :model="stationForm" :rules="rules1" label-width="100px" label-position="left">
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item prop="SEATNO" label="工位号：">
              <el-input v-model="stationForm.SEATNO" placeholder="请输入工位号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item prop="stationIp" label="工位IP：">
              <el-input v-model="stationForm.stationIp" placeholder="请输入工位IP"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item prop="SEATNAME" label="工位名称：">
              <el-input v-model="stationForm.SEATNAME" placeholder="请输入工位名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button size="mini" type="primary" icon="el-icon-plus" @click="createStation">创建工位</el-button>
          </el-col>
          <!-- <el-col :span="5">
            <el-button size="mini" type="success" icon="el-icon-plus" @click="assembleRoomInfo">组装房间信息</el-button>
          </el-col> -->
        </el-row>
      </el-form>

      <el-container>
        <el-container>
          <el-aside class="physical_left" width="1500px" height="613px">
            <!-- <el-col> -->
            <div>
              <canvas id="canvas" width="1500px" height="813px" style="border:1px solid black"></canvas>
            </div>
            <!-- </el-col> -->
            <el-dialog position="absolute" v-el-drag-dialog @dragDialog="handleDrag" title="工位信息 操作" width="400px"
              :modal="false" :center="true" :visible.sync="dialogVisible" @close="closeUser">
              <el-form size="mini" ref="dialogForm" :model="dialogForm" :rules="rules" label-width="80px"
                label-position="left">
                <el-row :gutter="10">
                  <el-col :span="20">
                    <el-form-item prop="SEATNO" label="工位号">
                      <el-input disabled v-model="dialogForm.SEATNO"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="20">
                    <el-form-item prop="SEATNAME" label="工位名称">
                      <el-input v-model="dialogForm.SEATNAME"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="20">
                    <el-form-item prop="SEATIP" label="工位IP:">
                      <el-input v-model="dialogForm.SEATIP" placeholder="请输入设备IP"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="20">
                    <el-form-item prop="LEFT" label="横坐标:">
                      <el-input-number size="mini" v-model="dialogForm.LEFT" :min="0" @change="changeSeatLeft">
                      </el-input-number>
                    </el-form-item>
                  </el-col>
                  <el-col :span="20">
                    <el-form-item prop="TOP" label="纵坐标:">
                      <el-input-number size="mini" v-model="dialogForm.TOP" :min="0" @change="changeSeatTop">
                      </el-input-number>
                    </el-form-item>
                  </el-col>
                  <el-col :span="20">
                    <el-form-item prop="SEATSTATUS" label="状态码">
                      <el-select v-model="dialogForm.SEATSTATUS" filterable placeholder="请选择状态">
                        <el-option v-for="item in STATUSLIST" :key="item.value" :label="item.name" :value="item.value">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="20">
                    <el-form-item prop="REMARK1" label="备注">
                      <el-input v-model="dialogForm.REMARK1" type="textarea" :rows="2" placeholder="请输入备注 "></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="10" class="dialogRow">
                  <el-col :span="6">
                    <el-button size="mini" type="primary" @click="updateStation">修改工位</el-button>
                  </el-col>
                  <el-col :span="6" :offset="8">
                    <el-button type="danger" size="mini" @click="delateStation">删除工位</el-button>
                  </el-col>
                </el-row>
              </el-form>
            </el-dialog>
          </el-aside>
        </el-container>
      </el-container>
    </el-card>
  </div>
</template>

<script>
  // 全局的参数
  import getGlobalParams from "@/common/utils/getGlobalParams";
  // 底图信息查询
  // import queryBackgroundImage from "@/message/siteManagement/workplacemonitoring/queryBackgroundImage";
  // 查询房间基本信息
  // import queryRoomInfo from "@/message/siteManagement/workplacemonitoring/queryRoomInfo";
  // 查询房间工位状态信息
  import seatManage from "@/message/siteManagement/workplacemonitoring/seatManage";
  //YYGl
  import requestYg from "@/common/utils/requestYg";
  // fabric依赖
  import {
    fabric
  } from "fabric";
  import elDragDialog from '@/common/utils/el-drag-dialog' // base on element-ui

  export default {
    directives: {
      elDragDialog
    },
    name: "",
    data() {
      return {
        // screenWidth:(document.body.clientWidth - 40)+'px',
        STATUSLIST: [{
            name: "有效",
            value: "1"
          },
          {
            name: "无效",
            value: "0"
          },
        ],
        // 后端可能会传的数据
        canvasObj: {},
        btnFlag: true,
        tableData: null,

        roomForm: {
          roomNo: "",
          roomName: "",
          stationSize: null,
          bkImageUrl: null,
          stationList: []
        },
        rules1: {
          SEATNO: [{
            required: true,
            message: "工位号必填",
            trigger: "blur"
          }],
          SEATNAME: [{
            required: true,
            message: "工位名称必填",
            trigger: "blur"
          }],
          stationIp: [{
            required: true,
            message: "设备IP必填",
            trigger: "blur"
          }],
        },
        rules: {
          SEATNO: [{
            required: true,
            message: "工位号必填",
            trigger: "blur"
          }],
          SEATNAME: [{
            required: true,
            message: "工位名称必填",
            trigger: "blur"
          }],
          SEATSTATUS: [{
            required: true,
            message: "工位状态必选",
            trigger: "change"
          }],
          LEFT: [{
            required: true,
            message: "工位横坐标必填",
            trigger: "blur"
          }],
          TOP: [{
            required: true,
            message: "工位纵坐标必填",
            trigger: "blur"
          }],
          SEATIP: [{
            required: true,
            message: "设备IP必填",
            trigger: "blur"
          }],
        },
        // bkImageUrlList: [],
        // 下拉框选择的底图后的数组，
        // changeBkImg: [],
        stationForm: {
          SEATNO: "",
          stationIp: "",
          SEATNAME: ''
        },
        stationMap: new Map(),
        stationIpMap: new Map(),
        visible: false,
        room: {},
        // 对话框
        dialogVisible: false,
        dialogForm: {
          SEATNO: "",
          SEATIP: "",
          SEATNAME: '',
          REMARK1: '',
          SEATSTATUS: '1',
          LEFT: 0,
          TOP: 0
        },
        dialogFormNew: {
          SEATNO: "",
          SEATIP: "",
          left: 0,
          top: 0
        }
      };
    },
    computed: {},
    created: function () {
      // console.log("created");
    },
    watch: {},
    mounted() {
      console.log("mounted");
      this.getParams();
    },

    methods: {
      // 查询房间关联的坐席
      async querySeat() {
        this.getRoomInfo = this.$route.params;
        let resBody = new seatManage();
        resBody.data.ROOMNO = this.getRoomInfo.roomNo;
        resBody.data.OPERFLAG = 'S'
        resBody.data.CURRPAGE = 1
        resBody.data.PAGEROWNUM = 200;
        resBody.data.PAGEFLAG = 4;
        let response = await requestYg(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.roomForm.stationList = response.RSP_BODY.struct
          if (this.getParams) {
            //  恢复房间数据：基本信息+工位数组；
            this.roomForm.roomName = this.getRoomInfo.roomName;
            this.roomForm.roomNo = this.getRoomInfo.roomNo;
              this.roomForm.bkImageUrl = this.getRoomInfo.bkImageUrl;
            this.roomForm.stationSize = this.getRoomInfo.stationSize;
            // this.roomForm.stationList = this.getRoomInfo.stationList;
            console.log("getParams内this.roomForm", this.roomForm);
            //  恢复创建房间：底图
            this.restoreRoom();
          }
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
      // v-el-drag-dialog onDrag Dialog可拖拽
      handleDrag() {},
      closeUser() {
        //关闭弹窗清楚表单数据并清楚表单验证
        // 重置表单数据
        this.$refs.dialogForm.clearValidate(); //清楚表单验证
        this.$refs.dialogForm.resetFields();
      },
      //获取上页数据，
      getParams() {
        console.log("this.$route.params=this.getRoomInfo,", this.$route.params);
        this.getRoomInfo = this.$route.params;
        if (this.getParams) {
          //  恢复房间数据：基本信息+工位数组；
          this.roomForm.roomName = this.getRoomInfo.roomName;
          this.roomForm.roomNo = this.getRoomInfo.roomNo;
          this.roomForm.bkImageUrl = this.getRoomInfo.bkImageUrl;
          this.roomForm.stationSize = this.getRoomInfo.stationSize;
          this.roomForm.stationList = this.getRoomInfo.stationList;
          console.log("getParams内this.roomForm", this.roomForm);
          //  恢复创建房间：底图
          this.restoreRoom();
        }
      },

      // // 远程请求图片数据
      // async query() {
      //   let resBody = new queryBackgroundImage();

      //   resBody.data.pageflag = "";
      //   resBody.data.IMAGEDESC = ""; //文字描述
      //   resBody.data.IMAGENO = ""; //图片号
      //   resBody.data.IMAGENAME = ""; //图片名

      //   console.log("底图query的resBody.data", resBody.data);
      //   requestYg(resBody)
      //     .then(response => {
      //       console.log("底图信息查询的response，", response);

      //       if (response.SYS_HEAD.ReturnCode === "000000") {

      //         this.tableData = response.RSP_BODY.Result || [];
      //         console.log("tableData,", this.tableData);
      //         //这里的地址在globalParams中配置  需要和后台的存放文件的配置统一
      //         //在这里只取图片下行地址中的ip地址
      //         //在表格中返回的内容只有相对地址，所以需要使用ip地址拼接
      //         var IpAddress = getGlobalParams.get(
      //           "WorkPlaceMonitorBackgroundImgDownloadUrl"
      //         );
      //         this.bkImageUrlList = this.tableData.map(item => {
      //           //  console.log("mounted的query的map中的item",item);
      //           return {
      //             value: IpAddress + item.IMAGENAME,
      //             name: item.IMAGEDESC,
      //             imgName: item.IMAGENAME,
      //             Url: item.URL
      //           };
      //         });
      //         console.log("query中的this.bkImageUrlList,", this.bkImageUrlList);

      //         // 底图下拉框查询完成后开始使用 上页传的数据后执行初始化所有工位；
      //         this.getParams();

      //       } else {
      //         this.$message({
      //           type: "error",
      //           message: response.SYS_HEAD.ReturnMessage
      //         });
      //         this.tableData = [];
      //       }
      //       this.loading = false;
      //     })
      //     .catch(error => {
      //       this.loading = false;
      //     });
      // },
      // 恢复创建房间方法
      restoreRoom() {
        console.log("恢复房间取用的this.roomForm,", this.roomForm);
        // console.log("恢复房间的this.bkImageUrlList", this.bkImageUrlList);

        //创建房间前先清除canvas画布
        var canvas;
        if (this.canvasObj.clear) {
          canvas = this.canvasObj;
          canvas.clear();
        } else {
          canvas = this.canvasObj = new fabric.Canvas("canvas");
        }
        // 显示画布
        this.visible = true;
        // 数据重置
        this.stationMap = new Map();
        //  工位Ip
        this.stationIpMap = new Map();
        // 去除交互
        canvas.interactive = false;
        // 创建房间CAD底图
        var self = this;
        fabric.Image.fromURL(self.roomForm.bkImageUrl, function (oImg) {
          // 匹配下拉框下的底图
          // 设置不可选择
          canvas.setBackgroundImage(oImg,null,{
            scaleX: canvas.width/oImg._element.width,
            scaleY: canvas.height/oImg._element.height
          });
          oImg.selectable = false;
          canvas.add(oImg);
          canvas.renderAll();
          self.canvasObj = canvas;
          console.log("恢复房间的add oImg的self.canvas,", self.canvasObj);
          // 恢复工位
          self.restoreStation();
        });
      },

      // 恢复工位
      restoreStation() {
        // 设置工位方块图默认属性
        const seatWidth = 50;
        const seatHeight = 50;
        const fontSize = 8;
        const _this = this;
        // 获取工位编号
        console.log("restoreStation,roomForm,", this.roomForm);
        var stationList = this.roomForm.stationList;
        // console.log("恢复工位前canvasObj,", this.canvasObj);
        console.log("恢复工位取用var的stationList:", stationList);
        if(stationList!=undefined){
        stationList.forEach(function (station, index) {
          // console.log("stationList--forEach的station,", station, index);
          var stationTop = parseInt(station.TOP);
          var stationLeft = parseInt(station.LEFT);
          station.initIconUrl = 'static/images/icons/icon/man-in.png'
          // station:恢复工位初始信息
          console.log("Start-forEach----canvasObj,", index, _this.canvasObj);
          // 创建工位
          fabric.Image.fromURL(station.initIconUrl, function (initIconImage) {
            // index:异步不确定；
            console.log("fromURL :index,", index, station);
            // 设置小图标
            initIconImage = initIconImage.scale(0.6).set({
              left: stationLeft + 14,
              top: stationTop + 2
            });
            // 绘制矩形
            var body = new fabric.Rect({
              width: seatWidth,
              height: seatHeight,
              left: stationLeft,
              top: stationTop,
              fill: " gray",
              rx: 10,
              ry: 10
            });
            // 工位号
            var SEATNO = new fabric.Text(station.SEATNO, {
              fontSize: 6,
              fill: "white",
              originX: "center",
              originY: "center",
              top: stationTop + 31,
              left: stationLeft + 20
            });
            // // 状态名称
            // var statusName = new fabric.Text(station.initStatusName, {
            //   fontSize: fontSize,
            //   fill: "white",
            //   originX: "center",
            //   originY: "center",
            //   top: stationTop + 43,
            //   left: stationLeft + 20
            // });
            // 工位名称
            var SEATNAME = new fabric.Text(station.SEATNAME, {
              fontSize: fontSize,
              fill: "white",
              originX: "center",
              originY: "center",
              top: stationTop + 43,
              left: stationLeft + 20
            });

            // 组合图片，
            var seatGroup = new fabric.Group(
              [body, SEATNO, initIconImage, SEATNAME], {
                // [body, SEATNO, statusName, initIconImage], {
                // 给每个seatGroup对应唯一的工位对象;
                station: station,
                // 锁住X,Y方向，不可缩放
                lockScalingX: true,
                lockScalingY: true
              }
            );
            _this.canvasObj.add(seatGroup).renderAll();
            // 往seatGroup塞工位编号，seatGroup要保存到canvas里面
            _this.stationMap.set(station.SEATNO, seatGroup);
            // 在本地塞工位IP，只为了识别工位IP的唯一性，上步已经保存到seatGroup;
            _this.stationIpMap.set(station.SEATIP, station.SEATNO);
            //  下面的打印都存在异步；不能确定 index的出现顺序；
            // console.log(
            //   "add------index,",
            //   index,
            //   "-SeatGroup-",
            //   seatGroup,
            //   "--stationMap-",
            //   _this.stationMap
            // );

            // 每个工位添加弹窗事件
            seatGroup.on("mouseup", function () {
              console.log(
                "seatGroup,",
                seatGroup,
                "station",
                station,
                "seatGroup.station,",
                seatGroup.station
              );
              console.log(
                "UP:left:",
                parseInt(seatGroup.left),
                ",top:",
                parseInt(seatGroup.top)
              );
              if (seatGroup.left < 0 || seatGroup.top < 0) {
                _this.$message.error('请不要移出底图外');
                _this.restoreRoom();
                return false
              }
              _this.dialogForm.SEATNO = station.SEATNO;
              _this.dialogForm.SEATIP = station.SEATIP;
              _this.dialogForm.SEATNAME = station.SEATNAME;
              _this.dialogForm.SEATSTATUS = station.SEATSTATUS;
              _this.dialogForm.seatOldIp = station.SEATIP;

              _this.dialogForm.LEFT = parseInt(seatGroup.left);
              _this.dialogForm.TOP = parseInt(seatGroup.top);

              console.log(" _this.dialogForm", _this.dialogForm);
              _this.dialogVisible = true;
            });
          });
          console.log("End---forEach----canvasObj,", index, _this.canvasObj);
        });
        }
      },

      // 点击 创建房间按钮事件
      createRoom() {
        console.log("creatRoom");

        // 所有输入必须有值
        // this.$refs["roomForm"].validate(valid => {
        console.log("roomForm.volid,", valid);
        if (valid) {
          console.log("创建房间取用的roomForm,", this.roomForm);
          // 创建房间前先清除canvas画布
          var canvas = null;
          if (this.canvasObj.clear) {
            canvas = this.canvasObj;
            canvas.clear();
          } else {
            canvas = this.canvasObj = new fabric.Canvas("canvas");
          }
          // 显示画布
          this.visible = true;
          // 数据重置
          this.stationMap = new Map();
          //  工位IP
          this.stationIpMap = new Map();
          // 去除交互
          canvas.interactive = false;
          // 创建房间CAD底图
          fabric.Image.fromURL(this.roomForm.bkImageUrl, function (oImg) {
            // 设置不可选择
            oImg.selectable = false;
            canvas.add(oImg);
          });
        } else {
          this.$message({
            type: "warning",
            message: "房间信息必须填写完整！"
          });
          return false;
        }
        // });
        console.log("创建房间后的canvasObj,", this.canvasObj);
      },

      // 点击创建工位按钮
      createStation() {
        console.log("createStation");
        console.log(
          "创建工位前canvasObj,",
          this.canvasObj,
          "this.stationIpMap,",
          this.stationIpMap,
          "roomForm,",
          this.roomForm
        );

        // 判断工位编号 是否存在
        if (!this.stationForm.SEATNO) {
          this.$message({
            type: "error",
            message: "工位不存在，请重新输入！"
          });
          return;
        }
        // 判断工位IP 是否存在
        if (!this.stationForm.stationIp) {
          this.$message({
            type: "error",
            message: "工位不存在，请重新输入！"
          });
          return;
        }

        // 获取工位编号
        const SEATNO = this.stationForm.SEATNO;
        const stationIp = this.stationForm.stationIp;
        const SEATNAME = this.stationForm.SEATNAME;
        // 判断工位是否存在
        if (this.stationMap.get(SEATNO)) {
          this.$message({
            type: "error",
            message: "工位已存在，请重新输入！"
          });
          return;
        }
        // 判读工位IP是否存在
        if (this.stationIpMap.get(stationIp)) {
          this.$message({
            type: "error",
            message: "工位IP已存在，请重新输入！"
          });
          return;
        }

        // 判断工位是否超过原先设定工位数;
        const mapLen = this.stationMap.size;
        const stationLen = parseInt(this.roomForm.stationSize);
        console.log("mapLen,", mapLen);
        console.log("stationLen,", stationLen);

        if (mapLen == stationLen) {
          this.$message({
            type: "error",
            message: "已创建【工位数】：( " +
              mapLen +
              " )  等于 ( " +
              stationLen +
              " )  请【增加工位数】或者【组装房间信息】"
          });
          return;
        }
        if (mapLen > stationLen) {
          this.$message({
            type: "error",
            message: "已创建【工位数】：( " +
              mapLen +
              " )  多于 ( " +
              stationLen +
              " )  请【删除工位】或者【增加工位数】"
          });
          return;
        }
        // 创建工位
        // 设置工位初始信息
        const station = {
          SEATNO,
          stationIp,
          SEATNAME,
          initStatusNo: "23", // 初始状态码都是23， 名称是未登录
          initStatusName: "未登录",
          initIconUrl: "static/images/icons/icon/man-in.png", // 初始图标URL,都是未登录图标
          left: 0,
          top: 0,
        };
        // 设置工位方块图默认属性
        const seatWidth = 50;
        const seatHeight = 50;
        const fontSize = 8;
        const _this = this;

        // 调用后台接口  新增工位信息
        let resBody = new seatManage();
        resBody.data.OPERFLAG = "I";
        resBody.data.ROOMNO = this.roomForm.roomNo; //房间号
        resBody.data.SEATNO = station.SEATNO; //工位号
        resBody.data.SEATNAME = station.SEATNAME; //工位名称
        resBody.data.SEATIP = station.stationIp; //工位IP
        // resBody.data.initIconUrl = station.initIconUrl; //图标
        // resBody.data.initStatusName = station.initStatusName; //状态名称
        // resBody.data.initStatusNo = station.initStatusNo; //状态码
        resBody.data.SEATSTATUS = '1' //状态码
        resBody.data.REMARK1 = station.REMARK1; //状态码
        resBody.data.LEFT = "" + station.left; //
        resBody.data.TOP = "" + station.top; //
        console.log("房间工位新增的resBody.data", resBody.data);
        requestYg(resBody)
          .then(response => {
            console.log("房间工位新增的response", response);
            if (response.SYS_HEAD.ReturnCode === "000000") {
              // 画工位方块图
              fabric.Image.fromURL(station.initIconUrl, function (initIconImage) {
                // 设置小图标
                initIconImage = initIconImage.scale(0.6).set({
                  left: station.left + 14,
                  top: station.top + 2
                });

                // 绘制矩形
                var body = new fabric.Rect({
                  width: seatWidth,
                  height: seatHeight,
                  left: station.left,
                  top: station.top,

                  fill: "gray",
                  rx: 10,
                  ry: 10
                });

                // 工位号 ：station.SEATNO
                var SEATNO = new fabric.Text(station.SEATNO, {
                  fontSize: 6,
                  fill: "white",
                  originX: "center",
                  originY: "center",
                  top: station.top + 31,
                  left: station.left + 18
                });
                // 状态名称
                // station.initStatusName
                // var statusName = new fabric.Text(station.initStatusName, {
                //   fontSize: fontSize,
                //   fill: "white",
                //   originX: "center",
                //   originY: "center",
                //   top: station.top + 43,
                //   left: station.left + 20
                // });
                // 工位名称
                var SEATNAME = new fabric.Text(station.SEATNAME, {
                  fontSize: fontSize,
                  fill: "white",
                  originX: "center",
                  originY: "center",
                  top: stationTop + 43,
                  left: stationLeft + 20
                });
                // 组合图片，
                var seatGroup = new fabric.Group(
                  [body, SEATNO, statusName, initIconImage],
                  // [body, statusName, initIconImage],
                  {
                    // 给每个seatGroup对应唯一的工位对象;
                    station: station,
                    // 锁住X,Y方向，不可缩放
                    lockScalingX: true,
                    lockScalingY: true
                  }
                );

                // 每个方块添加鼠标按下事件
                seatGroup.on("mouseup", function () {
                  console.log(
                    "seatGroup,",
                    seatGroup,
                    "station",
                    station,
                    "seatGroup.station,",
                    seatGroup.station
                  );
                  console.log(
                    "UP:left:",
                    parseInt(seatGroup.left),
                    ",top:",
                    parseInt(seatGroup.top)
                  );
                  if (seatGroup.left < 0 || seatGroup.top < 0) {
                    _this.$message.error('请不要移出底图外');
                    _this.restoreRoom();
                    return false
                  }
                  _this.dialogForm.SEATNO = station.SEATNO;
                  _this.dialogForm.SEATIP = station.stationIp;
                  _this.dialogForm.SEATNAME = station.SEATNAME;
                  _this.dialogForm.seatOldIp = station.stationIp;

                  _this.dialogForm.LEFT = parseInt(seatGroup.left);
                  _this.dialogForm.TOP = parseInt(seatGroup.top);
                  _this.dialogVisible = true;
                });

                // console.log("add的SeatGroup,", seatGroup);

                _this.canvasObj.add(seatGroup);
                _this.canvasObj.renderAll();
                _this.stationMap.set(SEATNO, seatGroup);
                _this.stationIpMap.set(stationIp, SEATNO);
              });
              // console.log(
              //   "创建工位后的this.stationMap,",
              //   this.stationMap,
              //   "stationIpMap,",
              //   this.stationIpMap
              // );
              // console.log("创建工位后的this.canvas,", this.canvasObj);

              this.$message({
                type: "success",
                message: "房间工位新增成功! 请不要忘记组装房间信息!"
              });
              this.querySeat()
            } else {
              this.$message({
                type: "danger",
                message: "房间工位新增失败! 原因： " + response.SYS_HEAD.ReturnMessage
              });
              this.loading = false;
            }
          })
          .catch(error => {
            this.loading = false;
          });
      },
      // 新增底图
      addBkImg() {
        this.$router.push({
          name: "ImageAdd"

        });
      },

      //点击  组装房间信息按钮 事件
      assembleRoomInfo() {
        // 判断工位是否过少或过多
        const mapLen = this.stationMap.size;
        const stationLen = parseInt(this.roomForm.stationSize);
        if (mapLen < stationLen) {
          this.$message({
            type: "error",
            message: "已创建【工位数】：( " +
              mapLen +
              " )  少于( " +
              stationLen +
              " ) 请继续【创建工位】或者【减少工位数】！"
          });
          return;
        }
        if (mapLen > stationLen) {
          this.$message({
            type: "error",
            message: "已创建【工位数】：( " +
              mapLen +
              " )  多于 ( " +
              stationLen +
              " ) 请【删除工位】或者【增加工位数】！"
          });
          return;
        }

        var _this = this;
        // var bkImg = this.bkImageUrlList.filter(function(ele, index) {
        //   console.log("handleChange,ele,", ele, index);
        //   return ele.value == _this.roomForm.bkImageUrl;
        // });

        // if (bkImg) {
        //   console.log("filter的bkImg，", bkImg);
        // }
        // 组装房间信息

        // console.log("addRoomInfo的this.roomForm,", this.roomForm);
        // console.log("addRoomInfo的this.changeBkImg,", this.changeBkImg);
        // console.log("addRoomInfo的this.bkImageUrlList,", this.bkImageUrlList);
        // let resBody = new queryRoomInfo();
        // resBody.data.oper_type = "U";
        // resBody.data.ROOMNAME = this.roomForm.roomName; //房间名称
        // resBody.data.ROOMNO = this.roomForm.roomNo; //房间号
        // resBody.data.SEATNO = "" + this.roomForm.stationSize; //工位数

        // resBody.data.URL = this.roomForm.bkImageUrl; //底图

        // resBody.data.IMAGENAME = this.changeBkImg[0]
        //   ? this.changeBkImg[0].imgName
        //   : bkImg[0].imgName;
        // resBody.data.IMAGEDESC = this.changeBkImg[0]
        //   ? this.changeBkImg[0].name
        //   : bkImg[0].name;
        // resBody.data.REMARK1 = "";
        // console.log("组装房间信息  发送resBady,", resBody.data);
        // requestYg(resBody)
        //   .then(response => {
        //     console.log("组装房间信息  response，", response);
        //     if (response.SYS_HEAD.ReturnCode === "000000") {
        //       this.$message({
        //         type: "success",
        //         message: "组装房间信息成功!"
        //       });
        //     } else {
        //       this.$message({
        //         type: "error",
        //         message: response.SYS_HEAD.ReturnMessage
        //       });
        //     }
        //     this.loading = false;
        //   })
        //   .catch(error => {
        //     this.loading = false;
        //   });
      },

      // 下拉框选择底图方法
      // handleChange(val) {
      //   console.log("handleChange,", val);
      //   console.log(this.bkImageUrlList);
      //   var bkImg = this.bkImageUrlList.filter(function(ele, index) {
      //     console.log("handleChange,ele,", ele, index);
      //     return ele.value == val;
      //   });
      //   console.log("bkImg", bkImg);
      //   this.changeBkImg = bkImg;
      // },

      // 改变横坐标 方块弹窗
      changeSeatLeft() {
        const SEATNO = this.dialogForm.SEATNO;
        const filterSeat = this.canvasObj._objects.filter(function (item, index) {
          return item.station && item.station.SEATNO === SEATNO;
        });
        const seat = filterSeat[0];
        // console.log("seat,", seat.station, seat);
        // console.log("dialogForm,", this.dialogForm);
        seat.left = this.dialogForm.LEFT;
        this.canvasObj.renderAll();
      },

      // 改变纵坐标 方块弹窗
      changeSeatTop() {
        const SEATNO = this.dialogForm.SEATNO;
        const filterSeat = this.canvasObj._objects.filter(function (item, index) {
          return item.station && item.station.SEATNO === SEATNO;
        });
        const seat = filterSeat[0];
        // console.log("seat,", seat.station, seat);
        // console.log("dialogForm,", this.dialogForm);

        seat.top = this.dialogForm.TOP;
        this.canvasObj.renderAll();
      },

      //  点击 修改工位按钮事件
      updateStation() {
        // 所有输入必须有值
        this.$refs["dialogForm"].validate(valid => {
          if (valid) {
            // 判读工位IP是否存在
            if (
              this.stationIpMap.get(this.dialogForm.SEATIP) &&
              this.dialogForm.seatOldIp !== this.dialogForm.SEATIP
            ) {
              this.$message({
                type: "error",
                message: "工位IP已存在，请重新输入！"
              });
              return;
            }
            // console.log("修改工位dialogForm，", this.dialogForm, "valid:", valid);

            const SEATNO = this.dialogForm.SEATNO;
            const filterSeat = this.canvasObj._objects.filter(function (
              item,
              index
            ) {
              // console.log("item,", item, index, item.station);
              return item.station && item.station.SEATNO === SEATNO;
            });

            const seat = filterSeat[0];
            // console.log(
            //   "根据工位号filterCanvas的当前工位对象seat.station,",
            //   seat.station
            // );

            seat.station.ROOMNO = this.roomForm.roomNo;
            seat.station.SEATIP = this.dialogForm.SEATIP;
            seat.station.left = "" + this.dialogForm.LEFT;
            seat.station.top = "" + this.dialogForm.TOP;
            seat.station.SEATNAME = "" + this.dialogForm.SEATNAME;
            seat.station.SEATSTATUS = "" + this.dialogForm.SEATSTATUS;

            // console.log(
            //   "seat.station",
            //   seat.station,
            //   this.dialogForm.LEFT,
            //   this.dialogForm.TOP
            // );
            // console.log("seat,", seat.station);

            let resBody = new seatManage();
            resBody.data.OPERFLAG = "U";
            (resBody.data.ROOMNO = seat.station.ROOMNO), //房间号
            (resBody.data.SEATNO = seat.station.SEATNO); //工位号
            resBody.data.SEATIP = seat.station.SEATIP; //工位IP
            resBody.data.SEATNAME = seat.station.SEATNAME; //工位IP
            // resBody.data.initIconUrl = seat.station.initIconUrl; //图标
            // resBody.data.initStatusName = seat.station.initStatusName; //状态名称
            resBody.data.SEATSTATUS = seat.station.SEATSTATUS; //状态码
            resBody.data.LEFT = seat.station.left; //left
            resBody.data.TOP = seat.station.top; //top
            // console.log("工位修改的resBody.data", resBody.data);
            requestYg(resBody)
              .then(response => {
                // console.log("工位修改的response", response);
                if (response.SYS_HEAD.ReturnCode === "000000") {
                  this.stationMap.get(SEATNO).station.SEATIP =
                    seat.station.SEATIP;
                  this.stationIpMap.set(this.dialogForm.seatOldIp, SEATNO);
                  // console.log(
                  //   "before----- this.stationIpMap,",
                  //   this.stationIpMap
                  // );
                  // console.log(
                  //   "stationMap.Ip,",
                  //   this.stationMap.get(SEATNO).station.SEATIP,
                  //   "seat.Ip,",
                  //   seat.station.SEATIP
                  // );
                  // console.log("更改后的stationMap", this.stationMap);

                  this.dialogForm.seatOldIp = seat.station.SEATIP;
                  // console.log("after--- dialogFOrm,", this.dialogForm);
                  // console.log("after-----IpMap,", this.stationIpMap);

                  this.dialogVisible = false;

                  this.$message({
                    type: "success",
                    message: "工位修改成功!请重新组装房间"
                  });
                  this.querySeat()
                } else {
                  this.dialogVisible = false;
                  this.$message({
                    type: "error",
                    message: "工位修改失败! 原因： " + response.SYS_HEAD.ReturnMessage
                  });
                }
              })
              .catch(error => {
                this.dialogVisible = false;
              });
          } else {
            this.$message({
              type: "warning",
              message: "工位信息必须填写完整！"
            });
            return false;
          }
        });
      },
      // 点击 删除工位 按钮
      delateStation() {
        this.$confirm("该条工位信息被删除, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(() => {
            this.paramDel();
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      },
      paramDel() {
        //删除
        const SEATNO = this.dialogForm.SEATNO;
        const SEATIP = this.dialogForm.SEATIP;
        const filterSeat = this.canvasObj._objects.filter(function (item, index) {
          return item.station && item.station.SEATNO === SEATNO;
        });
        const seat = filterSeat[0];
        // console.log("seat,", seat.station);

        let resBody = new seatManage();

        (resBody.data.ROOMNO = this.roomForm.roomNo), //房间号
        (resBody.data.SEATNO = this.dialogForm.SEATNO); //工位号

        resBody.data.OPERFLAG = "D";
        requestYg(resBody)
          .then(response => {
            // console.log("房间工位删除的response", response);
            if (response.SYS_HEAD.ReturnCode === "000000") {
              this.canvasObj.remove(seat);
              // console.log("remove后的canvas,", this.canvasObj);
              this.stationMap.delete(SEATNO);
              this.stationIpMap.delete(SEATIP);
              this.roomForm.stationSize--;
              // console.log(
              //   "删除后的stationMap,",
              //   this.stationMap,
              //   "stationIpMap,",
              //   this.stationIpMap
              // );

              this.canvasObj.renderAll();

              // console.log(
              //   "this.roomForm.stationSize:",
              //   this.roomForm.stationSize
              // );
              this.dialogVisible = false;

              this.$message({
                type: "success",
                message: "房间工位删除成功!"
              });
            } else {
              this.dialogVisible = false;
              this.$message({
                type: "waring",
                message: "房间工位删除失败! 原因： " + response.SYS_HEAD.ReturnMessage
              });
            }
          })
          .catch(error => {
            this.dialogVisible = false;
          });
      },

      // 返回上一页
      prev() {
        console.log("返回上一页");
        this.$router.go(-1);
      }
    }
  };

</script>


<style lang="scss" scoped>
  * {
    list-style-type: none;
  }


  .monitor {
    width: 100%;
    height: 35px;
    line-height: 33px;
    background-color: #f5f5f5;
    border-top: 1px solid #e5e5e5;
    border-bottom: 1px solid #e5e5e5;
    color: #208cf0;
    padding: 0px 35px;
    text-align: center;
  }

  .dialogStyle {
    position: absolute !important;
    left: 1200px !important;
    top: 0px !important;
  }

  .backBeforepage {
    display: inline-block;
    left: 10px;
    position: absolute;
  }

  .physical_left {
    position: relative;
    // border:1px  solid black;
  }

  .dialog-text {
    display: inline-block;
    width: 100%;
    text-align: center;
    color: red;
  }

  .clearfix:after {
    clear: both;
  }

  .el-card {
    width: 100%;
    overflow: inherit;
  }

  .el-form-item {
    margin-left: 30px;
  }

  .el-form-item1 {
    margin-left: 10px;
  }

  .box2-button {
    width: 80px;
  }

  .asideText {
    width: 100%;
    height: 35px;
    line-height: 33px;
    color: #409eff;
    text-align: center;
  }

  .dialogRow {
    margin-top: 20px;
  }

</style>
